import numpy as np
import matplotlib.pyplot as plt


def cal_polyfit(x, y, deg=2, isShow=0):
    # 拟合一个二次多项式
    coefficients = np.polyfit(x, y, deg)
    if (isShow == 1):
        fn = np.poly1d(coefficients)
        # 生成x值用于绘制拟合曲线
        x_fit = np.linspace(min(x), max(x), 100)
        y_fit = fn(x_fit)
        # 绘制数据点和拟合曲线
        plt.scatter(x, y, color='red', label='Data Points')
        plt.plot(x_fit, y_fit, color='blue', label='Fitted Curve')
        plt.xlabel('x')
        plt.ylabel('y')
        plt.legend()
        plt.title('Polynomial Fit')
        plt.show()
    return coefficients.tolist()


if __name__ == "__main__":
    y = [0.35, 0.3, 0.25, 0.2, 0.15, 0.1]
    x = [31.7, 25.5, 15.5, 7.8, 2.9, 0.6]
    deg = 2
    isShow = 1
    abc = cal_polyfit(x, y, deg, isShow)

    print(abc)
